package com.fdb.efp.nls.service.util;

import com.dc.open.file.client.ftp.FtpGet;
import com.dc.open.file.client.ftp.FtpPut;
import com.dc.open.file.server.msg.FileMsgBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Objects;

/**
 * 
 * 开放平台文件传输工具类
 * 
 * @author ludayong
 * @since 2019年1月7日 上午11:37:42
 * @version 1.0
 */
public class OpfFileUtil {
	private static Logger logger = LoggerFactory.getLogger(OpfFileUtil.class);

	public static boolean uploadFile(String localFile, String remoteFile, String scrtFlag) throws Exception {
		boolean result = false;
		FtpPut ftpPut = null;
		FileMsgBean bean = null;
		try {
			logger.info("上传文件到开发平台请求信息：" + localFile + "***********" + remoteFile + "***********" + scrtFlag);
			bean = new FileMsgBean();
			ftpPut = new FtpPut(localFile, remoteFile, scrtFlag, false, null);

			bean = ftpPut.doPutFile();
			Objects.requireNonNull(bean);// 返回结果不为空
			if ("000000".equals(bean.getFileMsgFlag())) {
				result = true;
			}
			logger.info("上传文件到开发平台响应信息：" + bean);
		} catch (Exception e) {
			// 捕获到异常后，可以从FileMsgBean类获取异常信息
			logger.error("上传文件到开放平台出现异常，错误码：" +( bean==null?"响应信息为空":bean.getFileRetMsg()) + "，异常信息" + e.getMessage());
			e.printStackTrace();
			throw new Exception("上传文件到开放平台出现异常，错误信息：" + bean, e);
		} finally {
			if (ftpPut != null) {
				ftpPut.close();
			}
		}
		return result;
	}

	public static boolean downloadFile(String localFile, String remoteFile, String scrtFlag) {
		boolean result = false;
		FtpGet ftpGet = null;
		FileMsgBean bean = null;
		try {
			bean = new FileMsgBean();
			ftpGet = new FtpGet(remoteFile, localFile, scrtFlag, false, null, bean);
			result = ftpGet.doGetFile();
			logger.info("从开发平台下载文件响应信息：" + bean);
		} catch (Exception e) {
			// 捕获到异常后，可以从FileMsgBean类获取异常信息
			logger.error("从开发平台下载文件出现异常，错误码：" + (bean==null?"响应信息为空":bean.getFileRetMsg()) + "，异常信息" + e.getMessage());
			e.printStackTrace();
		} finally {
			if (ftpGet != null) {
				ftpGet.close();
			}
		}
		return result;
	}
}
